package com.ggbbe.sip1;

import java.text.ParseException;

import android.support.v7.app.ActionBarActivity;
//import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.app.PendingIntent;
import android.content.Intent;
import android.net.sip.SipAudioCall;
import android.net.sip.SipException;
import android.net.sip.SipManager;
import android.net.sip.SipProfile;
import android.net.sip.SipRegistrationListener;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.util.Log;
//import android.os.Build;

public class WalkieTalkieActivity extends ActionBarActivity 
{
	
	public SipManager mSipManager = null;
	public SipAudioCall mCall = null;
	
	SipProfile mSipLocalProfile = null;
	SipProfile mSipPeerProfile = null;
	
	private final String usernameLocal = "krystian1201"; 
	private final String usernamePeer = "krystian1201_2";
	
	private SipAudioCall.Listener mAudioCallListener = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		if (savedInstanceState == null) 
		{
			getSupportFragmentManager().beginTransaction()
					.add(R.id.container, new PlaceholderFragment()).commit();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) 
	{

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) 
	{
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) 
		{
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	public void updateStatus(String msg)
	{
		TextView textViewStatus = (TextView)findViewById(R.id.textViewStatus);
		textViewStatus.setText(msg);
	}
	
	public SipProfile buildSIPProfile(String username)
	{
		SipProfile sipProfile = null;
		
		if(mSipManager == null) 
		{
		    mSipManager = SipManager.newInstance(this);
		    Log.d("SipManager", "new instance creted");
		}
		else
		{
			Log.d("SipManager", "no new instance");
		}
		
		
		String domain = "sip.linphone.org";
		//String proxy = "proxy.sipthor.net";
		
		String password = "npctkmzdc123";
		
		SipProfile.Builder builder = null;
		
		try 
		{
			builder = new SipProfile.Builder(username, domain);
		} 
		catch (ParseException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if (builder != null) 
		{
			builder.setPassword(password);
			//builder.setAuthUserName(username);
			//builder.setOutboundProxy(proxy);
			sipProfile = builder.build();
			Log.d("SipProfile", "Profile built successfully");
		}
		else 
		{
			Log.d("SipProfile", "Profile build failed");
		}
		
		return sipProfile;
		
	}
	
	public void SIPRegister()
	{
		Intent intent = new Intent();
		intent.setAction("android.SipDemo.INCOMING_CALL");
		PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, Intent.FILL_IN_DATA);
		
		try 
		{
			mSipManager.open(mSipLocalProfile, pendingIntent, null);
		} 
		catch (SipException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		final String tag = "RegistrationListener";
		
		try 
		{
			mSipManager.setRegistrationListener(mSipLocalProfile.getUriString(), new SipRegistrationListener() 
				{

					public void onRegistering(String localProfileUri) 
					{
						Log.d(tag, "Registering with SIP Server...");
					}

					public void onRegistrationDone(String localProfileUri, long expiryTime) 
					{
						Log.d(tag, "Ready");
					}
					   
					public void onRegistrationFailed(String localProfileUri, int errorCode,
					    String errorMessage) 
					{
						Log.d(tag, "Registration failed.  Please check settings." + 
					    		localProfileUri + errorCode + errorMessage);
					}
			
				}
			);
		} 
		catch (SipException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void closeLocalProfile() 
	{
	    if (mSipManager == null) 
	    {
	       return;
	    }
	    try 
	    {
	       if (mSipLocalProfile != null) 
	       {
	    	   	mSipManager.close(mSipLocalProfile.getUriString());
	       		Log.d("WalkieTalkieActivity/onDestroy", "Successfully closed local profile.");
	       }
	     } 
	    catch (Exception ee) 
	    {
	       Log.d("WalkieTalkieActivity/onDestroy", "Failed to close local profile.", ee);
	    }
	}
	
	public void setUpAudioCallListener()
	{
		SipAudioCall.Listener listener = new SipAudioCall.Listener() 
		{
			   @Override
			   public void onCallEstablished(SipAudioCall call) 
			   {
			      call.startAudio();
			      call.setSpeakerMode(true);
			      call.toggleMute();
			   }
			   
			   @Override
			   public void onCallEnded(SipAudioCall call) 
			   {
			      // Do something.
			   }
			};
	}
	
	public void startCall()
	{
		try 
		{
			mCall = mSipManager.makeAudioCall(mSipLocalProfile.getUriString(), mSipPeerProfile.getUriString(), mAudioCallListener, 30);
		} 
		catch (SipException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void onClickButtonRegister(View view)
	{
		mSipLocalProfile = buildSIPProfile(usernameLocal);
		mSipPeerProfile = buildSIPProfile(usernamePeer);
		
		SIPRegister();
		
		setUpAudioCallListener();
	}
	
	public void onClickButtonUnregister(View view)
	{
		closeLocalProfile();
	}
	
	public void onClickButtonStartCall(View view)
	{
		startCall();
	}
		
	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment 
	{

		public PlaceholderFragment() 
		{
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_main, container,
					false);
			return rootView;
		}
	}

}
